package cn.zbacm.api.security.controller;

import cn.zbacm.api.application.service.ApplicationService;
import cn.zbacm.api.security.CustomUser;
import cn.zbacm.api.security.dto.JwtAuthenticationResponse;
import cn.zbacm.api.security.dto.LoginDto;
import cn.zbacm.api.security.service.SecurityService;
import cn.zbacm.api.user.dto.UserDto;
import cn.zbacm.api.user.entity.User;
import cn.zbacm.api.util.ServiceResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class SecurityController {
  @Autowired
  private ApplicationService applicationService;

  @Autowired
  private SecurityService securityService;

  @Autowired
  private ModelMapper modelMapper;

  @GetMapping("/api/me")
  @ApiOperation(value = "获取当前用户信息")
  public ResponseEntity getCurrentUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof AnonymousAuthenticationToken) {
      return new ResponseEntity(HttpStatus.UNAUTHORIZED);
    }

    CustomUser customUser = (CustomUser) authentication.getPrincipal();
    User user = customUser.getUser();
    UserDto userDto = modelMapper.map(user, UserDto.class);
    return ResponseEntity.ok(userDto);
  }

  @PostMapping("/api/login")
  @ApiOperation(value = "密码登录", notes = "支持用户名、手机号、邮箱登录")
  public ResponseEntity login(@Valid @RequestBody LoginDto loginDto)
          throws JsonProcessingException {
    ServiceResult<String> result =
            securityService.authenticate(loginDto.getLoginId(), loginDto.getPassword());

    if (!result.getSuccess()) {
      return ResponseEntity.badRequest().body(result);
    }

    return ResponseEntity.ok(new JwtAuthenticationResponse(result.getData()));
  }
}
